<template>
      <div>
            <div class="search">
               <input v-model="putVal" type="text" placeholder="请输入城市名或拼音">
            </div>
            <div class="search_content" ref="wrapper" v-show="putVal">
              <ul>
                <li class="search_item"
                    v-for="(item,index) in list"
                    @click="handleCityClick(item.name)"
                >{{item.name}}</li>
                <li class="search_item" v-show="flag">没有匹配到数据</li>
              </ul>
            </div>
      </div>
</template>
<script>
    import BScroll from 'better-scroll'
    export default {
        name: "Search",
        props:{
          cities:Object //
        },
        data () {
           return {
             putVal:"",//
             list:[],//存储城市数组
             timer:null
           }
        },
        methods:{
          handleCityClick (city) {//点击城市
            this.$store.dispatch("changeCity",city);
            this.$router.push("/");//编程式路由
          }
        },
        computed :{
             flag () {
               return !this.list.length;
             }
        },
        watch : {//监听关键字的变化
          putVal () {
            if(this.timer){
              clearTimeout(this.timer);
            }
            this.timer=setTimeout(()=>{//函数截留
              var result=[];
              for (var i in this.cities){//循环数据对象
                this.cities[i].forEach((val)=>{
                  // console.log(val);
                  //查找关键字
                  if(val.name.indexOf(this.putVal) > -1 || val.spell.indexOf(this.putVal) >-1){
                    //找到了
                    result.push(val);
                  }
                })
              }
              this.list=result;
            },20)
          }
        },
        mounted () {
            this.scroll=new BScroll(this.$refs.wrapper);
        }
    }
</script>
<style lang="stylus" scoped>
   .search{
       height:.36rem;
       background :#00bcd4;
       padding:0 .1rem;
       input{
           box-sizing :border-box;
           width: 100%
           text-align:center;
           border-radius :.05rem;
           height:.31rem;
           line-height :.31rem;
           padding:0 .05rem;
           color:#666;
       }
   }
  .search_content{
      background:#cacaca;
      width:100%;
      position:absolute;
      top:.8rem;left:0;bottom:0;
      overflow :hidden;z-index:1;
      .search_item{
         line-height:.26rem;
         background :white;
         padding-left:.1rem;
         border-bottom :1px solid #cacaca;
      }
  }
</style>
